package com.baizhi.controller;

import com.baizhi.entity.Result;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("login")
    public Result login(String code,String username, String password, HttpServletRequest request){
        Result result = null;
        String securityCode = (String)request.getSession().getAttribute("securityCode");
        System.out.println(password+"======"+username);
        try{
            if(securityCode.equals(code)){
                User user = userService.login(username,password);
                result = new Result();
                result.setStatus(true);
                request.getSession().setAttribute("user", user);
            }else{
                throw new RuntimeException("验证码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @RequestMapping("findAll")
    @ResponseBody
    public List<User> findAll(){
        return userService.findAll();
    }

    @RequestMapping("findById")
    @ResponseBody
    public User findById(String id){
        return userService.findById(id);
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(User user){
        Result result = new Result();
        try{
            userService.update(user);
            result = new Result();
            result.setStatus(true);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("更新失败");
        }
        return result;
    }
}
